import os
import json
from datetime import datetime

class FileHandler:
    def __init__(self):
        self.base_path = "D:\\学生算题系统\\data"
        self.exam_path = os.path.join(self.base_path, "exams")
        self.submission_path = os.path.join(self.base_path, "submissions")
        self.analysis_path = os.path.join(self.base_path, "analysis")
        
        # 创建必要的文件夹
        for path in [self.exam_path, self.submission_path, self.analysis_path]:
            os.makedirs(path, exist_ok=True)
    
    def save_exam(self, exam_data):
        """保存试卷"""
        filename = f"exam_{exam_data['exam_id']}.json"
        filepath = os.path.join(self.exam_path, filename)
        with open(filepath, 'w', encoding='utf-8') as f:
            json.dump(exam_data, f, ensure_ascii=False, indent=2)
    
    def load_exam(self, exam_id):
        """加载试卷"""
        filepath = os.path.join(self.exam_path, f"exam_{exam_id}.json")
        with open(filepath, 'r', encoding='utf-8') as f:
            return json.load(f)
    
    def save_submission(self, submission_data):
        """保存答卷"""
        filename = f"submission_{submission_data['submission_id']}.json"
        filepath = os.path.join(self.submission_path, filename)
        with open(filepath, 'w', encoding='utf-8') as f:
            json.dump(submission_data, f, ensure_ascii=False, indent=2)
    
    def load_submission(self, submission_id):
        """加载答卷"""
        filepath = os.path.join(self.submission_path, f"submission_{submission_id}.json")
        with open(filepath, 'r', encoding='utf-8') as f:
            return json.load(f)
    
    def list_exams(self):
        """列出所有试卷"""
        exams = []
        for file in os.listdir(self.exam_path):
            if file.startswith('exam_') and file.endswith('.json'):
                exams.append(file[5:-5])
        return exams
    
    def save_analysis(self, student_name, analysis_data):
        """保存错题分析"""
        filename = f"analysis_{student_name}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
        filepath = os.path.join(self.analysis_path, filename)
        with open(filepath, 'w', encoding='utf-8') as f:
            json.dump(analysis_data, f, ensure_ascii=False, indent=2)
            
    def generate_wrong_questions_html(self, student_id, exam_id, analysis_data):
        """生成错题分析HTML页面"""
        if not os.path.exists(self.analysis_path):
            os.makedirs(self.analysis_path)
        
        # 生成错题表格行
        wrong_questions_rows = ""
        for wrong in analysis_data.get('wrong_questions', []):
            wrong_questions_rows += f"""
                <tr>
                    <td>{wrong['question']}</td>
                    <td class="wrong-answer">{wrong['student_answer']}</td>
                    <td class="correct-answer">{wrong['correct_answer']}</td>
                </tr>
            """
        
        # 计算正确和错误题目数量
        total = analysis_data['total_questions']
        wrong_count = len(analysis_data.get('wrong_questions', []))
        correct_count = total - wrong_count
        
        # HTML模板
        html_content = f'''
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="utf-8">
            <title>错题分析报告</title>
            <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
            <style>
                body {{
                    font-family: "Microsoft YaHei", sans-serif;
                    margin: 0;
                    padding: 20px;
                    background-color: #f0f2f5;
                }}
                .container {{
                    max-width: 1200px;
                    margin: 0 auto;
                }}
                .header {{
                    background: linear-gradient(135deg, #1a73e8, #289cf5);
                    color: white;
                    padding: 30px;
                    border-radius: 15px;
                    box-shadow: 0 4px 6px rgba(0,0,0,0.1);
                    margin-bottom: 30px;
                    text-align: center;
                }}
                .header h1 {{
                    margin: 0;
                    font-size: 2.5em;
                    font-weight: normal;
                }}
                .student-info {{
                    font-size: 1.2em;
                    margin-top: 15px;
                }}
                .score {{
                    font-size: 3.5em;
                    font-weight: bold;
                    margin: 20px 0;
                    text-shadow: 2px 2px 4px rgba(0,0,0,0.2);
                }}
                .charts-container {{
                    display: flex;
                    gap: 30px;
                    margin-bottom: 30px;
                }}
                .chart-box {{
                    flex: 1;
                    background: white;
                    padding: 20px;
                    border-radius: 15px;
                    box-shadow: 0 4px 6px rgba(0,0,0,0.1);
                }}
                .chart {{
                    height: 400px;
                }}
                .wrong-questions {{
                    background: white;
                    padding: 30px;
                    border-radius: 15px;
                    box-shadow: 0 4px 6px rgba(0,0,0,0.1);
                }}
                .wrong-questions h2 {{
                    color: #1a73e8;
                    margin-top: 0;
                    padding-bottom: 15px;
                    border-bottom: 2px solid #eee;
                    font-size: 1.8em;
                }}
                table {{
                    width: 100%;
                    border-collapse: collapse;
                    margin-top: 20px;
                    box-shadow: 0 2px 4px rgba(0,0,0,0.05);
                }}
                th {{
                    background: #f8f9fa;
                    color: #1a73e8;
                    padding: 15px;
                    text-align: left;
                    border-bottom: 2px solid #eee;
                    font-size: 1.1em;
                }}
                td {{
                    padding: 15px;
                    border-bottom: 1px solid #eee;
                    font-size: 1.1em;
                }}
                .wrong-answer {{
                    color: #dc3545;
                    font-weight: bold;
                    background-color: rgba(220, 53, 69, 0.1);
                    padding: 5px 10px;
                    border-radius: 4px;
                }}
                .correct-answer {{
                    color: #28a745;
                    font-weight: bold;
                    background-color: rgba(40, 167, 69, 0.1);
                    padding: 5px 10px;
                    border-radius: 4px;
                }}
                tr:hover {{
                    background-color: #f8f9fa;
                    transition: background-color 0.3s;
                }}
            </style>
        </head>
        <body>
            <div class="container">
                <div class="header">
                    <h1>错题分析报告</h1>
                    <div class="student-info">
                        学号：{student_id} | 试卷：{exam_id}
                    </div>
                    <div class="score">{analysis_data['score']} 分</div>
                </div>
                
                <div class="charts-container">
                    <div class="chart-box">
                        <div id="scoreChart" class="chart"></div>
                    </div>
                    <div class="chart-box">
                        <div id="wrongChart" class="chart"></div>
                    </div>
                </div>
                
                <div class="wrong-questions">
                    <h2>错题详情</h2>
                    <table>
                        <tr>
                            <th>题目</th>
                            <th>你的答案</th>
                            <th>正确答案</th>
                        </tr>
                        {wrong_questions_rows}
                    </table>
                </div>
            </div>
            
            <script>
                var scoreChart = echarts.init(document.getElementById('scoreChart'));
                var wrongChart = echarts.init(document.getElementById('wrongChart'));
                
                var scoreOption = {{
                    title: {{ 
                        text: '得分情况',
                        textStyle: {{
                            fontSize: 18,
                            fontWeight: 'normal'
                        }}
                    }},
                    series: [{{
                        type: 'gauge',
                        progress: {{ show: true }},
                        axisLine: {{
                            lineStyle: {{
                                width: 20,
                                color: [
                                    [0.6, '#dc3545'],
                                    [0.8, '#ffc107'],
                                    [1, '#28a745']
                                ]
                            }}
                        }},
                        pointer: {{ show: false }},
                        axisTick: {{ show: false }},
                        splitLine: {{ show: false }},
                        axisLabel: {{ show: false }},
                        detail: {{
                            valueAnimation: true,
                            formatter: '{{value}}分',
                            fontSize: 30,
                            fontWeight: 'bold',
                            offsetCenter: [0, '0%']
                        }},
                        data: [{{ value: {analysis_data["score"]} }}]
                    }}]
                }};
                
                var wrongOption = {{
                    title: {{ 
                        text: '答题情况分析',
                        textStyle: {{
                            fontSize: 18,
                            fontWeight: 'normal'
                        }}
                    }},
                    tooltip: {{
                        trigger: 'item',
                        formatter: '{{b}}: {{c}}题 ({{d}}%)'
                    }},
                    legend: {{
                        orient: 'horizontal',
                        bottom: 'bottom',
                        data: ['正确', '错误']
                    }},
                    series: [{{
                        name: '答题情况',
                        type: 'pie',
                        radius: ['40%', '70%'],
                        avoidLabelOverlap: false,
                        itemStyle: {{
                            borderRadius: 10,
                            borderColor: '#fff',
                            borderWidth: 2
                        }},
                        label: {{
                            show: true,
                            formatter: '{{b}}: {{c}}题'
                        }},
                        emphasis: {{
                            label: {{
                                show: true,
                                fontSize: 20,
                                fontWeight: 'bold'
                            }}
                        }},
                        data: [
                            {{ 
                                value: {correct_count}, 
                                name: '正确',
                                itemStyle: {{ color: '#28a745' }}
                            }},
                            {{ 
                                value: {wrong_count}, 
                                name: '错误',
                                itemStyle: {{ color: '#dc3545' }}
                            }}
                        ]
                    }}]
                }};
                
                scoreChart.setOption(scoreOption);
                wrongChart.setOption(wrongOption);
                
                window.addEventListener('resize', function() {{
                    scoreChart.resize();
                    wrongChart.resize();
                }});
            </script>
        </body>
        </html>
        '''
        
        # 固定文件名（不使用时间戳），实现覆盖
        html_file = os.path.join(self.analysis_path, f"analysis_{student_id}_{exam_id}.html")
        
        with open(html_file, 'w', encoding='utf-8') as f:
            f.write(html_content)
        
        return html_file